<?php
/**
 * Introduction: 支付
 * @author: 杨陈鹏
 * @date: 2016/4/7 23:00
 * @email: yangchenpeng@cdlinglu.com
 */

namespace App\Controller\Pay;


use Common\Controller\App\SignController;
use Think\Alipay\Alipay;
use Think\Wxpay\Wxpay;

class IndexController extends SignController
{
    /**
     * Introduction: 支付
     * @author: 杨陈鹏
     * @date: 2016/4/7 23:00
     * @email: yangchenpeng@cdlinglu.com
     */
    public function index()
    {


        $data = I('post.data');

        $order_logic = D('Common/Order','Logic');

        if(!$data['order_id'])
            outPut(['code' => 300,'msg' => '缺少订单信息!']);

        //检测库存
        $check = $order_logic::checkStorage($data['order_id']);


        if($check['code'] == 300)
            outPut($check,true);

        //检测订单中是否有已经下架的商品,如果有,则更改订单状态

        $check_goods_state = $order_logic::checkGoodsState($data['order_id']);

        if($check_goods_state['code'] == 300)
            outPut($check_goods_state,true);



        //获取订单信息

        $order = $order_logic::calcOrderTotalPrice($data['order_id']);

        $order_info['out_trade_no']     = $order['data']['number'];
        $order_info['subject']          = C('SMS_CONFIG.SMS_API_SIGN').'商品购买';
        $order_info['body']             = '您在'.C('SMS_CONFIG.SMS_API_SIGN').'的交易订单号为:'.$order['data']['number'].'。交易时间:'.date('Y-m-d H:i:s');

        $use = 0;


        $member_logic = D('Common/Member','Logic');

        //解冻当前订单中的资金,以防多次提交支付而多次冻结账户余额
        $balance_pay_nums = $order_logic::$model
                            ->where(['id' => $data['order_id']])
                            ->getField('balance_pay_nums');


        //outPut($balance_pay_nums);

        $member_logic::$model
                        ->where(['uid' => self::$uid])
                        ->setDec('frozen',$balance_pay_nums);


        //是否余额优先支付
        if($data['balanced'] === 'yes'){


            //获取当前用户账户信息
            $balance = $member_logic::$model
                ->where(['uid' => self::$uid])
                ->field('balance,frozen')
                ->find();


            //获取可以余额
            $use = intval($balance['balance']) - intval($balance['frozen']);

            //如果余额大于订单的支付余额,则直接支付成功
            if( $use >=  intval($order['data']['total'])){

                if($this->_pay($order['data']))
                {

                    //减去当前用户余额
                    $member_logic::$model
                        ->where(['uid' => self::$uid])
                        ->setDec('balance',$order['data']['total']);

                    outPut(['code' => 200,'msg' => '支付成功!' ,'data' => ['isOrderFinish' => true]]);

                } else {

                    outPut(['code' => 300, 'msg' => '支付失败']);

                }

            } else {

                //剩余的使用第三方支付
                $order['data']['total'] -= $use;

            }


        }
        //冻结资金
        $member_logic::$model
            ->where(['uid' => self::$uid])
            ->setInc('frozen',$use);

        //记录到当前订单当中
        $order_logic::$model
            ->where(['id' => $data['order_id']])
            ->save(['balance_pay_nums' => $use,'third_pay_nums' => intval($order['data']['total'])]);

        switch($data['payway'])
        {

            case 'alipay':

                $alipay = new Alipay();

                //支付宝支付金额的单位为元
                $order_info['total'] = sprintf("%.2f", (intval($order['data']['total']) / 100));

                outPut($alipay->signH5($order_info),true);

                break;

            case 'wxpay':

                $wxpay = new Wxpay();

                //微信金额的单位为分
                $order_info['total'] = intval($order['data']['total']);

                $result = $wxpay->signH5($order_info);

                //file_put_contents(RUNTIME_PATH.'wxpay-'.NOW_TIME.'.txt',json_encode($result));

                outPut($result,true);

                break;

            case 'balance':

                outPut(['code' => 300, 'msg' => '正在玩命开发中!'],true);

                break;

            default :

                outPut(['code' => 300, 'msg' => '支付失败,缺少支付信息!'],true);

                break;

        }

    }

    private function _pay($order_info)
    {

        //组装订单信息
        $order_data['pay_type'] = 3;
        //$order_data['third_number'] = $data['trade_no'];
        //$order_data['third_accounts'] = $data['buyer_email'];
        //$order_data['third_use_account'] = $data['buyer_id'];
        //$order_data['third_use_account'] = 2;
        $order_data['pay_time'] = NOW_TIME;
        $order_data['status'] = 2;

        $member_consumption['description'] = '(余额支付)';
        $member_consumption['time'] = NOW_TIME;
        $member_consumption['nums'] = $order_info['total'];//$data['total_fee'] * 100;


        $order_logic = D('Common/Order','Logic');

        //商品增加销量和减去库存
        $order_logic::success(['number' => $order_info['number']]);
        try{


            $model = M();

            //开启事物

            $model->startTrans();

            $member_consumption['uid'] = $model
                ->table( '__ORDER__' )
                ->where( [['number' => $order_info['number']]] )
                ->getField( 'uid' );

            //修改订单状态
            $res_order = $model
                ->table( '__ORDER__' )
                ->where( ['number' => $order_info['number']] )
                ->save($order_data);


            $res_member_consumption = $model
                ->table('__MEMBER_CONSUMPTION_RECORD__')
                ->add($member_consumption);





            if ( $res_order && $res_member_consumption ){
                //提交事物
                $model->commit();



                return true;
            }

            //事物回滚
            $model->rollback();

            return false;

        } catch (\Exception $e){

            file_put_contents(LOG_PATH.'balancepay_callback_error_'.$order_info['number'].'.log',$e->getMessage());

        }

    }

}